package com.wkk.controller;

import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {
	/**
	 * 登陆处理
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/logon", method = RequestMethod.POST)
	public String logon(HttpServletRequest req, Model model) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
		// 进行验证，这里可以捕获异常，然后返回对应信息
		String exception = null;

		try {
			subject.login(usernamePasswordToken);

		} catch (Exception e) {
			exception = e.getClass().getSimpleName();
		} finally {
			String msg = "";
			if (exception != null) {
				if (exception.equals("UnknownAccountException")) {
					msg = "账号不存在";
				} else if (exception.equals("IncorrectCredentialsException")) {
					msg = "密码不正确";
				} else {
					msg = "忙碌";
				}
				model.addAttribute("msg", msg);
				model.addAttribute("username", username);
				model.addAttribute("password", password);
				return "/login";
			}

		}
		model.addAttribute("username", username);
		return "/index";
	}

	/**
	 * 主页跳转
	 * 
	 * @return
	 */
	@RequestMapping(value = "/index")
	public String index() {
		/* Subject subject = SecurityUtils.getSubject(); */
		// 此处从数据库，根据该用户拥有角色，查询出不重复的权限（可访问目录）
		// 然后以map形式返回给主页model
		// 主页model根据吗map里的值显示可访问目录

		return "index";
	}

	/**
	 * 登陆页跳转
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login")
	public String login() {

		return "login";
	}

}
